$.config = {
    // 路由功能开关过滤器，返回 false 表示当前点击链接不使用路由
    routerFilter: function($link) {
        // 某个区域的 a 链接不想使用路由功能
        if ($link.is('.disable-router a')) {
            return false;
        }
        return true;
    }
};
var genre = getQueryString("genre");
var GET_URL = "/data/changjiaList/";
var MODIF_URL = "/data/changjia/";

$(function () {
    'use strict';
    //无限滚动
    $(document).on("pageInit", "#page-infinite-scroll-bottom", function(e, id, page) {
        var loading = false;
        // 每次加载添加多少条目
        var itemsPerLoad = 10;
        // 最多可加载的条目
        var maxItems = 1000;
        var lastIndex = $('.list-container li').length;

        $(page).on('infinite', function() {
            // 如果正在加载，则退出
            if (loading) return;
            // 设置flag
            loading = true;
            // 模拟1s的加载过程
            setTimeout(function() {
                // 重置加载flag
                loading = false;
                if (lastIndex >= maxItems) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    // 删除加载提示符
                    $('.infinite-scroll-preloader').remove();
                    return;
                }
                addItems();
                // 更新最后加载的序号
                lastIndex = document.getElementsByClassName("card").length;
                $.refreshScroller();
            }, 1000);
        });
    });


    $.init();
    changeRgb = function (cardHeader) {
        cardHeader.style.backgroundColor = rgb();
        if (rgbSum < 400) {
            cardHeader.style.color = "#FFF";
        }
    };
    window.onload=function(){
        addItems();
    };
});

/*文本框自适应*/
function setHeight(element) {
    $(element).css({'height':'auto','overflow-y':'hidden','background-color':'#f5f5f5;'}).height(element.scrollHeight);}
$('textarea').each(function () {
    setHeight(this);
}).on('input', function () {
    setHeight(this);
});

function addItems() {
    var cardF = document.getElementsByClassName("card")[0].cloneNode(true);
    cardF.style.display = "block";
    ajax({
        type:"get",
        url:GET_URL+genre,
        dataType:"json",
        beforeSend:function(){
        },
        success:function(data){
            if (data.code == 500)
                window.location.href = "/login.html";
            else if (data.data.length == 0){
                $.toast("厉害了 数据数据已经被你们查完了= =", 1000);
            }else
                $.toast("查询成功", 1000);

            for (var i = 0; i < data.data.length; i++) {
                d = data.data[i];

                var card = cardF.cloneNode(true);
                card.getElementsByTagName("form")[0].id = d.id;

                card.getElementsByClassName("card-header")[0].innerHTML = d.company;
                var inputs = card.getElementsByTagName("input");
                inputs[0].value = d.company;
                inputs[1].value = d.address;
                inputs[2].value = d.type;
                inputs[3].value = d.linkman;
                inputs[4].value = d.phone;
                inputs[5].value = d.telephone;
                inputs[6].value = d.linkman2;
                inputs[7].value = d.phone2;
                card.getElementsByTagName("textarea")[0].value = d.remark;
                card.getElementsByTagName("a")[0].href = "tel:"+d.phone;
                card.getElementsByTagName("a")[1].href = "tel:"+d.telephone;
                card.getElementsByTagName("a")[2].href = "tel:"+d.phone2;

                // card.getElementsByClassName("buttons-row")[0].firstElementChild.href = "/data/changjia/"+d.id;
                // card.getElementsByClassName("buttons-row")[0].lastElementChild.href = "/data/changjia/"+d.id;
                put = card.getElementsByClassName("button-success")[0];
                put.dataset.id = d.id;

                putA = card.getElementsByClassName("buttons-row")[0].lastElementChild;
                putA.dataset.id = d.id;

                putB = card.getElementsByClassName("buttons-row")[0].firstElementChild;
                putB.dataset.id = d.id;

                changeRgb(card.getElementsByClassName("card-header")[0]);
                $('.infinite-scroll .list-container').append(card);
                //加载完毕绑定事件
                put.onclick = function (putA) {//绑定优质按钮
                    clientPOST(this)
                };
                putA.onclick = function () {//绑定有效按钮
                    clientPut(this);
                };
                putB.onclick = function () {//绑定拉黑按钮
                    clientDelete(this)
                }
            }
        },
        error:function(){
            console.log("error")
        }
    });
}

/*随机标题背景色*/
var rgbSum = 0;
function rgb(){
    var r=Math.floor(Math.random()*255);
    var g=Math.floor(Math.random()*255);
    var b=Math.floor(Math.random()*255);
    var rgb='rgb('+r+','+g+','+b+')';
    rgbSum = r+g+b;
    return rgb;
}
changeRgb = function (c) {
    c.style.backgroundColor = rgb();
    if (rgbSum < 400) {
        c.style.color = "#FFF";
    }
};

//修改信息->标记为有效客户
function clientPut(node) {
    objId = node.dataset.id;
    from = document.getElementById(objId);
    var inputs = from.getElementsByTagName("input");

    $.ajax({
        url:MODIF_URL+objId,/*url也可以是json之类的文件等等*/
        type:'POST',/*DELETE、POST */
        data:{
            "_method" : "PUT",
            "id" : objId,
            "company" : inputs[0].value,
            "address" : inputs[1].value,
            "type" : inputs[2].value,
            "linkman" : inputs[3].value,
            "phone" : inputs[4].value,
            "telephone" : inputs[5].value,
            "linkman2" : inputs[6].value,
            "phone2" : inputs[7].value,
            "remark" : from.getElementsByTagName("textarea")[0].value
        },
        contentType : "application/x-www-form-urlencoded;charset=UTF-8",
        success:function (result) {
            if(result.code == 200){
                result.data == 1 ? $.toast("标记成功") : $.toast("某些原因导致标记失败了~");
            }else {
                $.toast("被某人抢先标记了~");
            }
        }
    })
}

function clientDelete(node) {
    objId = node.dataset.id;

    $.ajax({
        url: MODIF_URL+ objId, /*url也可以是json之类的文件等等*/
        type: 'POST', /*DELETE、POST */
        data: {
            "_method": "DELETE",
            "id": objId
        },
        success: function (result) {
            if (result.data == 1) {
                $.toast("拉黑成功");
            } else {
                $.toast("拉黑可能失败了~");
            }
        }
    })
}

function clientPOST(node) {
    objId = node.dataset.id;

    $.ajax({
        url: MODIF_URL + objId, /*url也可以是json之类的文件等等*/
        type: 'POST', /*DELETE、POST */
        data: {
            "_method": "POST",
            "id": objId
        },
        success: function (result) {
            if (result.data == 1) {
                $.toast("标记成功,他是你的了");
            } else {
                $.toast("标记失败,可能被抢先了");
            }
        }
    })
}

/*原生手写ajax*/
function ajax(){
    var ajaxData = {
        type:arguments[0].type || "GET",
        url:arguments[0].url || "",
        async:arguments[0].async || "true",
        data:arguments[0].data || null,
        dataType:arguments[0].dataType || "text",
        headers:arguments[0].headers || "",
        contentType:arguments[0].contentType || "application/x-www-form-urlencoded",
        beforeSend:arguments[0].beforeSend || function(){},
        success:arguments[0].success || function(){},
        error:arguments[0].error || function(){}
    };
    ajaxData.beforeSend();
    var xhr = createxmlHttpRequest();
    xhr.responseType=ajaxData.dataType;
    xhr.open(ajaxData.type,ajaxData.url,ajaxData.async);
    xhr.setRequestHeader("Content-Type",ajaxData.contentType);
    xhr.send(convertData(ajaxData.data));
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if(xhr.status == 200){
                ajaxData.success(xhr.response)
            }else{
                ajaxData.error()
            }
        }
    }
}

function createxmlHttpRequest() {
    if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
}

function convertData(data){
    if( typeof data === 'object' ){
        var convertResult = "" ;
        for(var c in data){
            convertResult+= c + "=" + data[c] + "&";
        }
        convertResult=convertResult.substring(0,convertResult.length-1);
        return convertResult;
    }else{
        return data;
    }
}

//获取参数地址栏参数
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}